package com.cskaoyan.market.admin.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.cskaoyan.market.admin.bo.ChannelBO;
import com.cskaoyan.market.admin.service.AdminOrderService;
import com.cskaoyan.market.admin.service.impl.AdminOrderServiceImpl;
import com.cskaoyan.market.db.domain.MarketOrder;
import com.cskaoyan.market.util.AdminResponseCode;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

/**
 * 订单管理模块相关接口
 *
 * @author BlackFlame33
 * @date 2023/03/20
 **/
@WebServlet("/admin/order/*")
public class AdminOrderController extends HttpServlet {
    private AdminOrderService adminOrderService = new AdminOrderServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/order", "");
        switch (op) {
            case "/list":
                getOrderList(req, resp);
                break;
            case "/detail":
                getOrderDetail(req, resp);
                break;
            case "/channel":
                getChannelList(req, resp);
                break;
            default:
                resp.setStatus(404);
        }
    }

    private void getOrderList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String[] orderStatusArrayParam = req.getParameterValues("orderStatusArray");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String start = req.getParameter("start");
        String end = req.getParameter("end");
        String userIdParam = req.getParameter("userId");
        String orderSn = req.getParameter("orderSn");
        if (StringUtils.isEmpty(pageParam) || StringUtils.isEmpty(limitParam) || StringUtils.isEmpty(sort)
                || StringUtils.isEmpty(order)) {
            pageParam = "1";
            limitParam = "20";
            sort = "add_time";
            order = "desc";
        }
        int page;
        int limit;
        Short[] orderStatusArray = null;
        if (orderStatusArrayParam != null) {
            orderStatusArray = new Short[orderStatusArrayParam.length];
        }
        Integer userId = null;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
            if (orderStatusArrayParam != null && !"".equals(orderStatusArrayParam[0])) {
                for (String status : orderStatusArrayParam) {
                    for (int i = 0; i < orderStatusArray.length; i++) {
                        orderStatusArray[i] = Short.valueOf((status));
                    }
                }
            }
            if (StringUtils.isNotEmpty(userIdParam)) {
                userId = Integer.valueOf(userIdParam);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgumentValue()));
            return;
        }
        List<MarketOrder> list =
                adminOrderService.getOrderList(page, limit, orderStatusArray, sort, order, start, end, userId, orderSn);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(list)));
    }

    private void getOrderDetail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String idParam = req.getParameter("id");
        if (StringUtils.isEmpty(idParam)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgumentValue()));
            return;
        }
        int id;
        try {
            id = Integer.parseInt(idParam);
        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgumentValue()));
            return;
        }
        Map<String, Object> data = adminOrderService.getOrderDetail(id);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(data)));
    }

    private void getChannelList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<ChannelBO> data = adminOrderService.getChannelList();
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(data)));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/order", "");
        switch (op) {
            case "/refund":
                refundOrder(req, resp);
                break;
            case "/ship":
                shipOrder(req, resp);
                break;
            case "/delete":
                deleteOrder(req, resp);
                break;
            case "/reply":
                reply(req, resp);
                break;
            default:
                resp.setStatus(404);
        }
    }

    private void reply(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        String commentId = JacksonUtil.parseString(requestBody, "commentId");
        String content = JacksonUtil.parseString(requestBody, "content");
        adminOrderService.reply(commentId, content);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
    }

    private void refundOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        Integer orderId = JacksonUtil.parseInteger(requestBody, "orderId");
        Integer refundMoney = JacksonUtil.parseInteger(requestBody, "refundMoney");
        Integer code = adminOrderService.refundOrder(orderId, BigDecimal.valueOf(refundMoney));
        if (code != 0) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail()));
        } else {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
        }
    }

    private void shipOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        Integer orderId = JacksonUtil.parseInteger(requestBody, "orderId");
        String shipChannel = JacksonUtil.parseString(requestBody, "shipChannel");
        String shipSn = JacksonUtil.parseString(requestBody, "shipSn");
        int code = adminOrderService.shipOrder(orderId, shipChannel, shipSn);
        if (code != 1) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail()));
        } else {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
        }
    }

    private void deleteOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        Integer orderId = JacksonUtil.parseInteger(requestBody, "orderId");
        int code = adminOrderService.deleteOrder(orderId);
        if (code != 1) {
            resp.getWriter().println(
                    JacksonUtil.writeValueAsString(ResponseUtil.fail(AdminResponseCode.ORDER_DELETE_FAILED, "订单不能删除")));
        } else {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
        }
    }
}